package com.gmscosmo.janus.echarts;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.gmscosmo.janus.echarts.*;
import com.gmscosmo.model.Node;
import com.gmscosmo.model.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class RedisClusterPoolUtilForEcharts {
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    private static final String PREFIX_SUBSCRIBERS = "SUBSCRIBERS";
    private static final String PREFIX_PRODUCERS = "PRODUCERS";
    private static final String PREFIX_USER_NODE = "USER_NODE";
    private static final String PREFIX_NODE_INFO = "NODE_INFO";
    private static final String PREFIX_ROOM_INFO = "ROOM_INFO";
    private static final String PREFIX_USER_ROOM = "USER_ROOM";
    private static final String PREFIX_PORT = "PORT";
    private static final boolean CLEAR = false;

    public void getRedis(String prefix, boolean del) {
        Set<String> keys = redisTemplate.keys(prefix + "*");
        for (String key : keys) {
            System.out.println(key + "：" + redisTemplate.opsForValue().get(key));
            if (del) {
                redisTemplate.delete(key);
            }
        }
    }

    public int getJanusServerNum(HashMap<Integer, String> janusNodeHostMap, HashMap<String, Point> janusServerNodes, HashMap<String, Point> interJanusServerNodes) {
        Set<String> keys = redisTemplate.keys(PREFIX_NODE_INFO + "*");
        for (String key : keys) {
            if (CLEAR) {
                redisTemplate.delete(key);
            }
            String nodeInfo = redisTemplate.opsForValue().get(key);
            ConcurrentHashMap<Integer, Node> nodeInfos = JSON.parseObject(nodeInfo, new TypeReference<ConcurrentHashMap<Integer, Node>>() {
            });
            for (Node node : nodeInfos.values()) {
                janusNodeHostMap.put(node.getNodeId(), node.getHost());
                Point point = new Point();
                point.setName("节点:" + node.getNodeId() + "\\nhost:" + node.getHost() + "\\n在线人数:" + node.getParticipant());
                point.setSymbolSize(150 + 50 * node.getParticipant());
                janusServerNodes.put(node.getHost(), point);
                interJanusServerNodes.put(node.getInterHost(), point);
//                        System.out.println("多人音视频服务器 节点:"+node.getNodeId()+" host:"+node.getHost() +" 在线人数:"+ node.getParticipant());
            }
            return nodeInfos.size();
        }

        return 0;
    }

    /**
     * 获取当前在进行的多人音视频房间数量
     *
     * @return
     */
    public int getRoomNum(HashMap<String, Point> roomNodes) {
        Set<String> all = new HashSet<>();
        Set<String> keys = redisTemplate.keys(PREFIX_ROOM_INFO + "*");
        for (String key : keys) {
            if (CLEAR) {
                redisTemplate.delete(key);
            }
            Point point = new Point();
            point.setSymbolSize(500);
            point.setName("Room:" + key.split(":")[1]);
            ItemStyle itemStyle = new ItemStyle();
            itemStyle.setOpacity(0.7);
            Random random = new Random();
            int color = 100000 + random.nextInt(55535);
            itemStyle.setColor("#" + color);
            point.setItemStyle(itemStyle);
            roomNodes.put(key.split(":")[1], point);
//                    System.out.println(key.SPLIT(":")[1]+":"+jedis.get(key));
        }
        all.addAll(keys);
        return all.size();
    }

    public void getParticipantRoom(HashMap<String, Point> roomNodes, HashMap<String, Point> participantNodes) {
        for (String userId : participantNodes.keySet()) {
            String roomId = redisTemplate.opsForValue().get(PREFIX_USER_ROOM + ":" + userId);
            if(roomId==null){
                continue;
            }
            Point room = roomNodes.get(roomId.replaceAll("\"", ""));
            if (room == null) {
                continue;
            }
            Point user = participantNodes.get(userId);
            Random random = new Random();
            room.setSymbolSize(room.getSymbolSize() + 20);
            user.setX(room.getX() + random.nextInt(room.getSymbolSize() / 4) - room.getSymbolSize() / 8);
            user.setY(room.getY() + random.nextInt(room.getSymbolSize() / 4) - room.getSymbolSize() / 8);
            user.setSymbolSize(room.getSymbolSize() / 5);
            participantNodes.put(userId, user);
        }
    }

    public int getParticipantNum(HashMap<Integer, String> janusNodeHostMap, List<Link> links, HashMap<String, Point> janusServerNodes, HashMap<String, Point> participantNodes) {
        Set<String> all = new HashSet<>();
        Set<String> keys = redisTemplate.keys(PREFIX_USER_NODE + "*");
        for (String key : keys) {
            if (CLEAR) {
                redisTemplate.delete(key);
            }
            Point point = new Point();
            point.setSymbolSize(50);
            point.setName(key.split(":")[1]);
            ItemStyle itemStyle = new ItemStyle();
            itemStyle.setOpacity(1.0);
            Random random = new Random();
            String color = "";
            for (int i = 0; i < 6; i++) {
                color += random.nextInt(10);
            }
            itemStyle.setColor("#" + color);
            point.setItemStyle(itemStyle);
            Link link = new Link();
            link.setSource(key.split(":")[1]);
            Point janus = janusServerNodes.get(janusNodeHostMap.get(Integer.valueOf(redisTemplate.opsForValue().get(key))));
            if(janus==null){
                continue;
            }
            link.setTarget(janus.getName());
            Label label = new Label();
            label.setFormatter("connected");
            link.setLabel(label);
            links.add(link);
//                    System.out.println(key.SPLIT(":")[1]+":"+jedis.get(key));
            participantNodes.put(key.split(":")[1], point);
        }
        all.addAll(keys);
        return all.size();
    }

    public int getPortNum() {
        Set<String> all = new HashSet<>();
        Set<String> keys = redisTemplate.keys(PREFIX_PORT + "*");
        all.addAll(keys);
        return all.size();
    }

    public void getRtpForwardData(List<Link> links, HashMap<String, Point> janusServerNodes, HashMap<String, Point> interJanusServerNodes) {
        int i = 1;
        Set<String> keys = redisTemplate.keys(PREFIX_PRODUCERS + "*");
        for (String key : keys) {
            if (CLEAR) {
                redisTemplate.delete(key);
            }
            List<Producer> producers = JSONObject.parseObject(redisTemplate.opsForValue().get(key), new TypeReference<List<Producer>>() {
            });
            for (Producer producer : producers) {
                Link link = new Link();
                if (janusServerNodes.containsKey(producer.getOriginHost())) {
                    link.setSource(janusServerNodes.get(producer.getOriginHost()).getName());
                } else {
                    link.setSource(interJanusServerNodes.get(producer.getOriginHost()).getName());
                }
                if (janusServerNodes.containsKey(producer.getHost())) {
                    link.setTarget(janusServerNodes.get(producer.getHost()).getName());
                } else {
                    link.setTarget(interJanusServerNodes.get(producer.getHost()).getName());
                }
                LineStyle lineStyle = new LineStyle();
                lineStyle.setCurveness(0.05 * i++);
                link.setLineStyle(lineStyle);
                Label label = new Label();
                label.setFormatter(producer.getRoom() + "=" + key.replace("PREFIX_PRODUCERS:", "") + "|" + producer.getOriginHost() + ">-----rtp_forward----->" + producer.getRtpForwardTo() + "|" + producer.getHost() + ":A" + producer.getAudio_port() + "/V" + producer.getVideo_port());
                link.setLabel(label);
//                        System.out.println(producer.getRoom()+"="+producer.getDisplay()+"|"+producer.getOriginHost()+">-----rtp_forward----->"+producer.getRtpForwardTo()+"|"+producer.getHost()+":A"+producer.getAudio_port()+"/V"+producer.getVideo_port());
                links.add(link);
            }
        }
    }
}
